package com.ruoyi.school.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.school.domain.dto.ImportSexOneOneDTO;
import com.ruoyi.school.service.ExcelImportService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ExcelImportServiceImpl implements ExcelImportService {

    private static final String STUDENT_ID_HEADER = "学号";

    @Override
    public List<ImportSexOneOneDTO> importExcel(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 1. 读取Excel原始数据
            List<Map<String, Object>> dataList = readExcel(inputStream);
            ObjectMapper objectMapper = new ObjectMapper();

            // 2. 按学号分组
            Map<String, List<Map<String, Object>>> groupedByStuNumber = dataList.stream()
                    .collect(Collectors.groupingBy(
                            row -> parseStuNumber(row.get(STUDENT_ID_HEADER))
                    ));

            // 3. 处理每组数据：移除学号字段，再转为JSON
            List<ImportSexOneOneDTO> result = new ArrayList<>();
            for (Map.Entry<String, List<Map<String, Object>>> entry : groupedByStuNumber.entrySet()) {
                String stuNumber = entry.getKey();
                List<Map<String, Object>> studentDataList = entry.getValue();

                // 关键步骤：遍历当前学号的所有行数据，移除学号字段
                studentDataList.forEach(row -> row.remove(STUDENT_ID_HEADER));

                // 4. 序列化处理后的列表为JSON（此时已不含学号字段）
                String importText = objectMapper.writeValueAsString(studentDataList);

                // 封装DTO
                ImportSexOneOneDTO dto = new ImportSexOneOneDTO();
                dto.setStuNumber(stuNumber);
                dto.setImportText(importText);
                result.add(dto);
            }

            return result;
        } catch (JsonProcessingException e) {
            throw new IOException("JSON序列化失败：" + e.getMessage(), e);
        }
    }


    // 解析Excel中的学号（处理可能的类型转换问题）
    private String parseStuNumber(Object stuNumberObj) {
        if (stuNumberObj == null) {
            throw new IllegalArgumentException("Excel中存在空的学号字段");
        }

        // 统一转换为字符串处理（兼容各种原始类型）
        String stuNumber;
        if (stuNumberObj instanceof String) {
            // 原始类型是字符串，直接trim去空格
            stuNumber = ((String) stuNumberObj).trim();
        } else if (stuNumberObj instanceof Number) {
            // 数字类型（如Double/Integer）：转为字符串（避免科学计数法）
            // 例如 12345.0 -> "12345"，123 -> "123"
            stuNumber = String.valueOf(((Number) stuNumberObj).longValue());
        } else {
            // 其他类型（如日期等不合法类型）
            throw new IllegalArgumentException("不支持的学号类型：" + stuNumberObj.getClass().getName());
        }

        // 校验学号是否为空（trim后）
        if (stuNumber.isEmpty()) {
            throw new IllegalArgumentException("学号为空字符串");
        }

        return stuNumber;
    }

//    @Override
//    public String importExcel(MultipartFile file) throws IOException {
//        // 检查文件是否为空
//        if (file.isEmpty()) {
//            throw new IllegalArgumentException("上传的文件为空");
//        }
//
//        // 读取Excel并转换为JSON
//        try (InputStream inputStream = file.getInputStream()) {
//            List<Map<String, Object>> dataList = readExcel(inputStream);
//            ObjectMapper objectMapper = new ObjectMapper();
//            return objectMapper.writeValueAsString(dataList);
//        }
//    }


    private List<Map<String, Object>> readExcel(InputStream inputStream) throws IOException {
        List<Map<String, Object>> dataList = new ArrayList<>();
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

        // 获取表头行
        Row headerRow = sheet.getRow(0);
        List<String> headers = new ArrayList<>();
        if(headerRow == null){
            throw new BaseException("表头为空");
        }
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            headers.add(headerRow.getCell(i).getStringCellValue());
        }

        // 遍历数据行（从第2行开始）
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            Map<String, Object> rowData = new HashMap<>();
            for (int j = 0; j < headers.size(); j++) {
                Cell cell = row.getCell(j);
                rowData.put(headers.get(j), getCellValue(cell));
            }
            dataList.add(rowData);
        }

        workbook.close();
        return dataList;
    }

    private Object getCellValue(Cell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue();
                } else {
                    return cell.getNumericCellValue();
                }
            case BOOLEAN:
                return cell.getBooleanCellValue();
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }
}
